#!/usr/bin/env python

from optparse import OptionParser
import sys, os

if not 'MQ_LOG_LEVEL' in os.environ:
    os.environ['MQ_LOG_LEVEL'] = '-1'

sys.path.insert(0, 'build/lib.macosx-10.5-i386-2.5')
from imq import MQConnection, MQMessage
from imq import MQ_BROKER_HOST_PROPERTY, MQ_BROKER_PORT_PROPERTY, MQ_CONNECTION_TYPE_PROPERTY, \
    MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE, MQ_QUEUE_DESTINATION, MQ_TOPIC_DESTINATION, \
    MQ_TEXT_MESSAGE, MQ_MESSAGE_TYPE_HEADER_PROPERTY, MQ_STRING_TYPE, MQ_INT32_TYPE



def producer(host, port, name, type):
    conn = MQConnection({ MQ_BROKER_HOST_PROPERTY : (MQ_STRING_TYPE, host),
            MQ_BROKER_PORT_PROPERTY : (MQ_INT32_TYPE, port),
            MQ_CONNECTION_TYPE_PROPERTY : (MQ_STRING_TYPE, "TCP")}, "guest", "guest")
    sess = conn.create_session(False, MQ_CLIENT_ACKNOWLEDGE, MQ_SESSION_SYNC_RECEIVE)
    prod = sess.create_producer_for_destination(sess.create_destination(name, type))
    mess = MQMessage(MQ_TEXT_MESSAGE)
    index = 0

    try:
        while True:
            text = raw_input("Enter a message to send:").strip()

            if 0 == len(text):
                break

            index += 1

            mess.set_properties({'index' : (MQ_INT32_TYPE, index,)})
            mess.set_headers({MQ_MESSAGE_TYPE_HEADER_PROPERTY : (MQ_STRING_TYPE, "my-type",)})
            mess.set_text(text)
            prod.send(mess)
    finally:
        mess.set_text("END")
        prod.send(mess)



if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("--host", action="store", dest="host", default="localhost")
    parser.add_option("--port", action="store", dest="port", default=7676, type="int")
    parser.add_option("--destination_name", action="store", dest="destination_name", default="example_producerconsumer_dest")
    parser.add_option("--type", action="store", dest="type", choices=("q", "t",), default="q")
    (options, args) = parser.parse_args()

    args = {'host' : options.host, 'port' : options.port, 'name' : options.destination_name,
        'type' : 't' == options.type and MQ_TOPIC_DESTINATION or MQ_QUEUE_DESTINATION}

    producer(**args)
